package cascade.components
{
	import flash.desktop.NativeApplication;
	import flash.display.NativeMenu;
	import flash.display.NativeMenuItem;
	import flash.events.Event;
	
	public class MenuHelper
	{
		public static function xmlToMainMenu(xml:XML):void {
			if (NativeApplication.supportsMenu)
				NativeApplication.nativeApplication.menu = xmlToMenu(xml);
		}
		
		public static function xmlToMenu(xml:XML):NativeMenu {
			var menu:NativeMenu = new NativeMenu();
			
			for each (var node:XML in xml.*) {
				var item:NativeMenuItem = new NativeMenuItem(node.@label, node.name() == "separator");
				
//				if (node.@icon.length())
//					item.icon = new getDefinitionByName(node.@icon)();
				
				var index:int = item.label.search(/(^|[^&])&([^&])/);
				if (index != -1) {
					item.label.replace(/&/, "");
					item.mnemonicIndex = index;
				}
				
				if (node.@enabled.length())
					item.enabled = node.@enabled;
				
				item.data = {};
				
				if (node.@data.length())
					item.data.arg = node.@data.toString();
				
				if (node.@command.length()) {
					item.data.action = node.@command.toString();
					item.addEventListener(Event.SELECT, selectedHandler);
				}
				
				if (node.*.length())
					item.submenu = xmlToMenu(node);
				menu.addItem(item);
			}
			
			return menu;
		}
		
		private static function selectedHandler(event:Event):void {
			var item:NativeMenuItem = event.target as NativeMenuItem;
			if (item.data.arg)
				Function(Cascade.cascade[item.data.action]).call(null, item.data.arg);
			else
				Cascade.cascade[item.data.action]();
		}
		
	}
}